import React from 'react';
import { withRouter } from 'react-router-dom';

import { Button, Input, Space, Table, Popconfirm, Descriptions, notification as Notification } from 'antd';
import { deleteUser, listUser } from '../../../api/user';
import { DownOutlined, PlusOutlined, ReloadOutlined, RightOutlined, SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';

import './UserList.scss';
import UserForm from './components/UserForm';

// account: "admin"
// avatar: ""
// createBy: ""
// createTime: null
// deleted: false
// email: "134@qq.com"
// enabled: true
// id: 1
// phone: ""
// remark: "902e9e8b7105ffdf0730590b7261d245"
// sex: "1"
// updateBy: "admin"
// updateTime: "2020-09-07 10:48:42"
// username: "admin"

class UserList extends React.Component {
  state = {
    tableHeight: 400,
    data: [],
    userForm: {
      visible: false,
      type: 'add',
      user: {}
    },
    pagination: {
      current: 1,
      pageSize: 10,
      total: 1,
      showTotal: (total) => `Total ${total} items`,
      hideOnSinglePage: false
    },
    tableParam: {},
    loading: false,
    searchText: {}
  };

  componentDidMount() {
    const { pagination } = this.state;
    this.fetch(pagination);

    window.addEventListener('resize', this.handleResize);
    setTimeout(() => {
      this.handleResize();
    }, 1);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  handleResize = (e) => {
    const element = document.getElementsByClassName('user-table-wrapper')[0];
    if (element) {
      const offsetHeight = element.offsetHeight;
      const tableHeight = offsetHeight - 64 - 58 - 4;
      this.setState({
        tableHeight: tableHeight
      });
    }
  };

  getColumnSearchProps = (dataIndex, placeholder) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            this.searchInput = node;
          }}
          placeholder={placeholder}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 130, marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 60 }}>
            清空
          </Button>
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined/>}
            size="small"
            style={{ width: 60 }}
          >
            查找
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }}/>,
    onFilter: (value, record) => true,
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select(), 100);
      }
    },
    render: (text) => {
      const searchText = this.state.searchText[dataIndex];
      return searchText ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (text);
    }
  });

  handleSearch = (selectedKeys, confirm, dataIndex) => {
    const { searchText } = this.state;
    const state = Object.assign(searchText, {
      [dataIndex]: selectedKeys && selectedKeys[0]
    });
    this.setState(state);
    confirm();
  };

  handleReset = (clearFilters) => {
    clearFilters();
    const state = Object.assign(this.state, {
      searchText: ''
    });
    this.setState(state);
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { account, sex } = filters;
    const { field, order } = sorter;
    console.log(sorter, typeof sorter, 'sorter');

    const user = {
      account: account && account[0],
      sex: sex && sex[0],
      sortField: field,
      order: order && order.replace('end', '')
    };

    this.setState({
      tableParam: user
    });
    this.fetch(pagination, user);
  };

  setUserForm = (userForm) => {
    this.setState({
      userForm: Object.assign(this.state.userForm, userForm)
    });
    this.handleRefresh();
  };

  handleUserDelete = ({ id: userId }) => {
    deleteUser(userId).then(({ data }) => {
      Notification.success({
        message: `删除${data.username}成功`,
        duration: 2
      });
      this.handleRefresh();
    }).catch((e) => {
      console.log(e, typeof e, 'e');
    });
  };

  handleUserEdit = (user) => {
    this.setUserForm({
      visible: true,
      type: 'edit',
      user
    });
  };

  handleRefresh= () => {
    this.fetch(this.state.pagination, this.state.tableParam);
  };

  fetch = (pagination = {}, user = {}) => {
    this.setState({ loading: true });
    const { current: pageNum, pageSize } = pagination;

    listUser(pageNum, pageSize, user).then(({ data }) => {
      const { pageNum, pageSize, total, list } = data;

      const pagination = Object.assign(this.state.pagination, {
        current: pageNum,
        pageSize: pageSize,
        total: total
      });

      this.setState({
        data: list,
        pagination
      });
    }).catch((e) => {
      console.log(e, typeof e, 'listUser e');
    }).finally(() => {
      this.setState({ loading: false });
    });
  };

  render() {
    const { data, pagination, loading, tableHeight, userForm } = this.state;
    const { visible: userFormVisible, type: userFormType, user } = userForm;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'username',
        // sorter: true,
        // render: (name) => `${name.first} ${name.last}`,
        width: 200,
      },
      {
        title: '学号',
        dataIndex: 'account',
        width: 130,
        sorter: true,
        sortDirections: ['ascend', 'descend', 'ascend'],
        ...this.getColumnSearchProps('account', '请输入查找学号'),
      },
      {
        title: '性别',
        dataIndex: 'sex',
        render: (sex) => {
          switch (sex) {
            case '0':
              return '女';
            case '1':
              return '男';
            case '2':
              return '保密';
            default:
              return '未知';
          }
        },
        filters: [
          { text: '男', value: '1' },
          { text: '女', value: '0' },
          { text: '保密', value: '2' },
        ],
        filterMultiple: false,
        width: 130,
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        width: 130,
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        width: 200,
      },
      // {
      //   title: '创建者',
      //   dataIndex: 'createBy',
      //   width: 130,
      // },
      // {
      //   title: '创建时间',
      //   dataIndex: 'createTime',
      //   width: 200,
      // },
      // {
      //   title: '更新者',
      //   dataIndex: 'updateBy',
      //   width: 130,
      // },
      // {
      //   title: '最近更新时间',
      //   dataIndex: 'updateTime',
      //   width: 200,
      // },
      // {
      //   title: '备注',
      //   dataIndex: 'remark',
      //   width: 300,
      // },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 300,
        render: (text, record) => {
          if (record.aaa) {
            return '';
          }
          return (
            <Space size="middle">
              <a onClick={() => this.handleUserEdit(record)}>修改</a>
              <Popconfirm
                title="确认删除?"
                cancelText="取消"
                okText="确定"
                okType=""
                onConfirm={() => this.handleUserDelete(record)}>
                <a>删除</a>
              </Popconfirm>
            </Space>
          );
        }
      },
    ];
    const setUpClassName = (record, index) => {
      if (record) {
        return '';
      }
    };

    const expandable = {
      expandIcon: ({ expanded, onExpand, record }) =>
        expanded ? (
          <DownOutlined onClick={(e) => onExpand(record, e)}/>
        ) : (
          <RightOutlined onClick={(e) => onExpand(record, e)}/>
        ),
      expandIconColumnIndex: 5,
      expandedRowRender: (record) => (
        <Descriptions
          bordered
          title="更多信息"
          column={1}
        >
          <Descriptions.Item label="创建者:">{record.createBy}</Descriptions.Item>
          <Descriptions.Item label="创建时间:">{record.createTime}</Descriptions.Item>
          <Descriptions.Item label="更新者:">{record.updateBy}</Descriptions.Item>
          <Descriptions.Item label="最近更新时间:">{record.updateTime}</Descriptions.Item>
          <Descriptions.Item label="备注:">{record.remark}</Descriptions.Item>
        </Descriptions>
      ),
      rowExpandable: (record) => true,
    };

    const handleUserAdd = () => {
      this.setUserForm({
        visible: true,
        type: 'add',
        user: {}
      });
    };

    const closeUserForm = () => {
      this.setUserForm({
        visible: false,
        type: 'add',
        user: {}
      });
    };

    return (
      <div className="user-list-container">
        <Space style={{ marginBottom: 10 }}>
          <Button type="primary" icon={<ReloadOutlined/>} onClick={this.handleRefresh} disabled={loading} loading={loading}>刷新</Button>
          <Button type="primary" icon={<PlusOutlined/>} onClick={handleUserAdd}>添加</Button>
        </Space>
        <UserForm visible={userFormVisible} type={userFormType} user={user} onClose={closeUserForm}/>
        <div className="user-table-wrapper">
          <Table
            columns={columns}
            rowClassName={setUpClassName}
            rowKey={(user) => user.id}
            dataSource={data}
            pagination={pagination}
            loading={loading}
            bordered
            showSorterTooltip={false}
            onChange={this.handleTableChange}
            expandable={expandable}
            scroll={{ y: tableHeight }}
          />
        </div>
      </div>
    );
  }
}

export default withRouter(UserList);
